/**
 * 
 */
package rounda2009;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

/**
 * @author Coddy created on 2010-5-21
 * 
 */
public class Happiness
{
	// static String currentInput = "B-small-attempt2.in";
	// static String currentOutput = "B-small-attempt2.out";

	static String currentInput = "input.in";
	static String currentOutput = "output.out";

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		try
		{
			// input
			BufferedReader bf = new BufferedReader(new FileReader(currentInput));
			BufferedWriter bw = new BufferedWriter(
					new FileWriter(currentOutput));
			int temp = Integer.parseInt(bf.readLine());
			int baseCount;
			int bases[] = new int[10];
			for (int testcase = 0; testcase < temp; testcase++)
			{
				baseCount = 0;

				String line = bf.readLine();
				StringTokenizer tokenizer = new StringTokenizer(line);
				while (tokenizer.hasMoreElements())
				{
					bases[baseCount++] = Integer.parseInt((String) tokenizer
							.nextElement());
				}
				bw.write("Case #" + (testcase + 1) + ": "
						+ findHappyNumber(bases, baseCount));
				bw.write("\n");
			}
			bw.flush();
		} catch (Exception e)
		{
			// TODO: handle exception
		}
		System.out.println("Finished!");
	}

	public static int findHappyNumber(int[] bases, int baseCount)
	{
		int happyNumber = 1;
		boolean found = false;
		while (!found)
		{
			boolean tFound = true;
			happyNumber++;

			for (int i = 0; i < baseCount; i++)
			{
				if (!isHappyNumber(happyNumber, bases[i]))
				{
					tFound = false;
					break;
				}
			}
			if (tFound)
			{
				found = true;
			}
		}
		return happyNumber;
	}

	public static boolean isHappyNumber(int number, int base)
	{
		Set historyResult = new HashSet<Integer>();
		int result = calculateSquareSum(Integer.toString(number, base));
		while (result != 1)
		{
			if (historyResult.contains(result))
			{
				return false;
			}
			historyResult.add(result);
			result = calculateSquareSum(Integer.toString(result, base));

		}
		return true;

	}

	private static int calculateSquareSum(String string)
	{
		int count = 0;
		for (int i = 0; i < string.length(); i++)
		{
			String ch = string.substring(i, i + 1);
			int j = Integer.parseInt(ch);
			count += j * j;
		}
		return count;
	}
}